package com.app.scale.record;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.scale.R;
import com.app.scale.basis.BasisActivity;
import com.app.scale.basis.Constants;
import com.app.scale.bean.BaseListBean;
import com.app.scale.bean.LoginBean;
import com.app.scale.bean.RecordListBean;
import com.app.scale.bean.RecordListData;
import com.app.scale.greendao.GreenDaoUtils;
import com.app.scale.scale.ScaleActivity;
import com.app.scale.util.MyUtils;
import com.app.scale.util.ReadCardUtils;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.clj.fastble.data.BleDevice;
import com.jaredrummler.materialspinner.MaterialSpinner;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import my.ActivityTool;
import my.LogUtil;
import my.SystemParamsUtils;
import my.TimeUtils;
import my.ViewUtils;
import my.http.MyHttpListener;
import my.http.MyHttpUtils;
import my.http.MyParams;

/**
 * 交易记录
 */
public class RecordListActivity extends BasisActivity {

    @BindView(R.id.recyclerview)
    XRecyclerView mRecyclerView;
    private MyAdapterList mAdapter;
    private RecordListBean mListBean;


    @BindView(R.id.text_start_time)
    TextView textStartTime;
    @BindView(R.id.text_end_time)
    TextView textEndTime;
    Calendar calendarStart;
    Calendar calendarEnd;

    @BindView(R.id.spinner)
    MaterialSpinner spinner;

    //U口读卡器,类似于外接键盘
    private ReadCardUtils readCardUtils;
    private String cardNo;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void initViews() {
        setContentView(R.layout.record_list_activity);
        setTitle("交易记录");
        setTitleBg(R.color.base_blue);
        setTitleLeftButton(null);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setVerticalScrollBarEnabled(true);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        mRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                mListBean.refresh();
                getList();
            }

            @Override
            public void onLoadMore() {
                getList();
            }
        });
        mRecyclerView.setPullRefreshEnabled(true);
        mRecyclerView.setLoadingMoreEnabled(true);
        initCalendar();

        //读卡器声明
        readCardUtils = new ReadCardUtils();
        initCardReader();
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        mListBean = new RecordListBean();
        setListView();
        setTitleLeftButton(null);

        spinner.setItems(getResources().getStringArray(R.array.isgua));
        spinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {

            @Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
                mRecyclerView.refresh();
            }
        });

        getList();
    }

    private void  initCalendar(){
//        calendarStart = Calendar.getInstance();
//        calendarStart.add(Calendar.MONTH, 0);
//        calendarStart.set(Calendar.DAY_OF_MONTH, 1);

        calendarStart = Calendar.getInstance();
        calendarStart.set(Calendar.HOUR_OF_DAY,0);
        calendarStart.set(Calendar.MINUTE,0);
        calendarStart.set(Calendar.SECOND,0);
        calendarStart.set(Calendar.MILLISECOND,0);


        calendarEnd = Calendar.getInstance();
        calendarEnd.set(Calendar.HOUR_OF_DAY,0);
        calendarEnd.set(Calendar.MINUTE,0);
        calendarEnd.set(Calendar.SECOND,0);
        calendarEnd.set(Calendar.MILLISECOND,0);
        textStartTime.setText(calendarStart == null? "": TimeUtils.getTimeByDate(calendarStart.getTime(), "yyyy-MM-dd"));
        textEndTime.setText(calendarEnd == null? "":TimeUtils.getTimeByDate(calendarEnd.getTime(), "yyyy-MM-dd"));
    }

    private void setListView() {
        if (mAdapter == null) {
            mAdapter = new MyAdapterList();
            mRecyclerView.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
    }

    private void onListViewComplete() {
        mRecyclerView.refreshComplete();
        mRecyclerView.loadMoreComplete();
        mRecyclerView.setLoadingMoreEnabled(mListBean.hasNextPage());
//        mRecyclerView.setLoadingMoreEnabled(false);
        setEmptyView();
    }

    private void setEmptyView() {
        if (mListBean == null || mListBean.getList().size() == 0) {
            findViewById(R.id.refresh_view).setVisibility(View.VISIBLE);
            findViewById(R.id.refresh_view).setOnClickListener(
                    new View.OnClickListener() {
                        public void onClick(View v) {
                            mRecyclerView.refresh();
                        }
                    });
        } else {
            findViewById(R.id.refresh_view).setVisibility(View.INVISIBLE);
        }
    }

    private void getList() {
        MyParams params = new MyParams();
        showProgress();
        params.put("aid", LoginBean.getInstance().getAid());
        params.put("ufs", LoginBean.getInstance().getUfs());
        params.put("uno", LoginBean.getInstance().getUno());
        params.put("mid", "11");
        params.put("sty", (spinner.getSelectedIndex()));
        if(!LoginBean.getInstance().isAdmin()){
            params.put("wno", SystemParamsUtils.getAndroidID(mContext));
        }
        params.put("bstime", textStartTime.getText().toString().trim());
        params.put("betime", textEndTime.getText().toString().trim());

        params.put(BaseListBean.PAGE_NAME, mListBean.getNextPage());
        if(!TextUtils.isEmpty(cardNo)){
            params.put("cdno", (cardNo));
            params.put(BaseListBean.PAGE_SIZE_NAME, 100);
        } else {
            params.put(BaseListBean.PAGE_SIZE_NAME, BaseListBean.PAGE_SIZE);
        }


        MyHttpUtils.get(Constants.URL_LEAF_SELECT_PAGE, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        if (isFinishing()) return;
                        RecordListBean recordListBean = (RecordListBean) result;
                        mListBean.addListBean(recordListBean);
                        setListView();
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
                        super.onFailure(httpWhat, result);
                        mListBean.getList().clear();
                        setListView();
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        dismissProgress();
                        onListViewComplete();
                        cardNo = "";
                    }
                },
                0, RecordListBean.class);

    }


    public class MyAdapterList extends RecyclerView.Adapter<MyAdapterList.ViewHolder> {

        public MyAdapterList() {

        }

        //创建新View，被LayoutManager所调用
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.record_list_item, viewGroup, false);
            return new ViewHolder(view);
        }

        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(ViewHolder viewHolder, int position) {
            viewHolder.bind(position);
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return mListBean == null ? 0 : mListBean.getList().size();
        }

        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.list_item)
            public View list_item;
            @BindView(R.id.text_no)
            public TextView text_no;
            @BindView(R.id.text_wno)        //单号
            public TextView text_wno;
            @BindView(R.id.text_tid)
            public TextView text_tid;
            @BindView(R.id.text_cna)
            public TextView text_cna;
            @BindView(R.id.text_una)
            public TextView text_una;
            @BindView(R.id.text_jna)
            public TextView text_jna;
            @BindView(R.id.text_tje)
            public TextView text_tje;


            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }

            public void bind(int position) {
                RecordListData data = mListBean.getList().get(position);
                MyUtils.setNotNullText(text_no,""+data.getTdt());
                MyUtils.setNotNullText(text_wno,""+data.getWno());
                MyUtils.setNotNullText(text_tid,""+data.getTid());
                MyUtils.setNotNullText(text_cna,""+data.getCna());
                MyUtils.setNotNullText(text_una,""+data.getUna());
                MyUtils.setNotNullText(text_jna,""+data.getJna());
                MyUtils.setNotNullText(text_tje,""+data.getTje());
                list_item.setTag(data);
            }

            @OnClick(R.id.list_item)
            public void onItemClick(View v) {
                RecordListData data = (RecordListData) v.getTag();
                Bundle extras = new Bundle();
                extras.putSerializable("data", data);
                ActivityTool.skipActivityForResult(mContext,RecordInfoActivity.class,extras,WARNLISTRESULT);
            }

        }
    }

    public final static int WARNLISTRESULT = 44;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == WARNLISTRESULT){
            mListBean.refresh();
            getList();
        }
    }

    @OnClick(R.id.view_filter_1)
    void timeBeginChoose() {
        //时间选择器
        TimePickerView pvTime = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                if (calendarStart == null) {
                    calendarStart = Calendar.getInstance();
                }
                calendarStart.setTime(date);
                onTimeBeginChoosed();
            }
        })
                .addOnCancelClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                    }
                })
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .build();
        pvTime.show();
        ViewUtils.hideInput(mContext);
    }

    void onTimeBeginChoosed() {
        textStartTime.setText(calendarStart == null? "":TimeUtils.getTimeByDate(calendarStart.getTime(), "yyyy-MM-dd"));
        if(calendarStart != null && calendarEnd != null){
            mRecyclerView.refresh();
        }else if(calendarStart == null && calendarEnd == null){
            mRecyclerView.refresh();
        }
    }

    @OnClick(R.id.view_filter_2)
    void timeEndChoose() {
        //时间选择器
        TimePickerView pvTime = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                if (calendarEnd == null) {
                    calendarEnd = Calendar.getInstance();
                }
                calendarEnd.setTime(date);
                onTimeEndChoosed();
            }
        }).addOnCancelClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .build();
        pvTime.show();
        ViewUtils.hideInput(mContext);
    }

    void onTimeEndChoosed() {
        textEndTime.setText(calendarEnd == null? "":TimeUtils.getTimeByDate(calendarEnd.getTime(), "yyyy-MM-dd"));
        if(calendarStart != null && calendarEnd != null){
            mRecyclerView.refresh();
        }else if(calendarStart == null && calendarEnd == null){
            mRecyclerView.refresh();
        }
    }

    /**
     * 读卡器初始化
     *  读卡器数据获取
     */
    private void initCardReader() {
        readCardUtils.setReadSuccessListener(new ReadCardUtils.OnReadSuccessListener() {
            @Override
            public void onScanSuccess(String barcode) {
                LogUtil.d("barcode: " + barcode);
                cardNo = barcode;
                mRecyclerView.refresh();
            }
        });
    }

    /**
     * 帮助读卡器
     *  当edittext没有获取焦点的时候   截取数据
     */
    @SuppressLint("RestrictedApi")
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (ReadCardUtils.isInputFromReader(this, event)) {
            if (readCardUtils != null){
                readCardUtils.resolveKeyEvent(event);
            }
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }
}
